package com.cfcc.deptone.assetbarcodemgr.activity;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cfcc.deptone.assetbarcodemgr.BuildConfig;
import com.cfcc.deptone.assetbarcodemgr.R;
import com.cfcc.deptone.assetbarcodemgr.constant.AiisConstants;
import com.cfcc.deptone.assetbarcodemgr.constant.AssetConstants;
import com.cfcc.deptone.assetbarcodemgr.utils.PandianFileUtils;
import com.cfcc.jaf.crypto.CryptoUtil;
import com.cfcc.jaf.crypto.JAFCryptoException;
import com.cfcc.jaf.crypto.sm.SMUtil;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.apache.commons.io.FileUtils;
import org.bouncycastle.math.ec.ECPoint;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private EditText resultEditView;
    private Bundle searchRecodeBundle;

    private final MainRecvHandler searchRecvHandler = new MainRecvHandler(this);

    private static byte[] pubx = CryptoUtil.toByteArray(AiisConstants.PUBX);
    private static byte[] puby = CryptoUtil.toByteArray(AiisConstants.PUBY);
    private static ECPoint pubKey = SMUtil.createECPoint(pubx, puby);
    private static byte[] prvKey = CryptoUtil.toByteArray(AiisConstants.PRVKEY);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        resultEditView = (EditText) findViewById(R.id.et_scan_result);

        Button scanBarcodeBtn = (Button) findViewById(R.id.btn_scan_barcode);

        Button searchBarcodeBtn = (Button) findViewById(R.id.btn_search_barcode);

        Button searchCheckinBtn = (Button) findViewById(R.id.btn_search_checkin);

        Button searchNoCheckinBtn = (Button) findViewById(R.id.btn_search_nocheckin);

        Button fileImportBtn = (Button) findViewById(R.id.btn_file_import);

        Button fileExportBtn = (Button) findViewById(R.id.btn_file_export);

        Button fileClearBtn = (Button) findViewById(R.id.btn_file_clear);

        Button aboutBtn = (Button) findViewById(R.id.btn_about);

        fileClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String filepath = MainActivity.this.getFilesDir().getAbsoluteFile() + File.separator + AssetConstants.PANDIAN_TMPFILE_NAME;
                    File tempFile = new File(filepath);
                    //如果临时文件存在
                    if (tempFile.exists()) {
                        FileUtils.forceDelete(tempFile);
                    }
                    filepath = Environment.getExternalStorageDirectory().getPath() + File.separator + AssetConstants.PANDIAN_FILE_NAME;
                    File importFile = new File(filepath);
                    //如果需要导入的文件存在
                    if (importFile.exists()) {
                        FileUtils.forceDelete(importFile);
                    }
                    filepath = Environment.getExternalStorageDirectory().getPath() + File.separator + AssetConstants.PANDIAN_EXPFILE_NAME;
                    File exportFile = new File(filepath);
                    //如果导出的文件存在
                    if (exportFile.exists()) {
                        FileUtils.forceDelete(exportFile);
                    }
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_CLEAR_SUCCESS, Toast.LENGTH_LONG).show();
                } catch (IOException ex) {
                    Log.e(TAG, ex.getMessage());
                    Logger.e(ex.getMessage());
                }
            }
        });

        aboutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, BuildConfig.VERSION_NAME, Toast.LENGTH_LONG).show();
            }
        });

        //文件导入
        fileImportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File destFile = new File(MainActivity.this.getFilesDir().getAbsoluteFile() + File.separator + AssetConstants.PANDIAN_TMPFILE_NAME);
                //如果解密的文件存在
                if (destFile.exists()) {
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_IMPORT_DEST_EXIST, Toast.LENGTH_LONG).show();
                    Logger.d(AssetConstants.MSG_BARCODE_FILE_IMPORT_DEST_EXIST);
                    return;
                }
                String filepath = Environment.getExternalStorageDirectory().getPath() + File.separator + AssetConstants.PANDIAN_FILE_NAME;
                File srcFile = new File(filepath);
                //如果需要导入的文件不存在
                if (!srcFile.exists()) {
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_IMPORT_SRC_NOTEXIST, Toast.LENGTH_LONG).show();
                    Logger.d(AssetConstants.MSG_BARCODE_FILE_IMPORT_SRC_NOTEXIST);
                    return;
                }

                //解密到目标文件
                try {
                    CryptoUtil.writeFile(SMUtil.decryptBySM2(prvKey, CryptoUtil.readFile(srcFile)), destFile);
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_IMPORT_SUCCESS, Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                    Logger.e(e.getMessage());
                } catch (JAFCryptoException e) {
                    Log.e(TAG, e.getMessage());
                    Logger.e(e.getMessage());
                }
            }
        });

        //文件导出
        fileExportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File srcFile = new File(MainActivity.this.getFilesDir().getAbsoluteFile() + File.separator + AssetConstants.PANDIAN_TMPFILE_NAME);
                //如果解密的文件存在
                if (!srcFile.exists()) {
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_EXPORT_SRC_NOTEXIST, Toast.LENGTH_LONG).show();
                    Logger.d(AssetConstants.MSG_BARCODE_FILE_EXPORT_SRC_NOTEXIST);
                    return;
                }
                String filepath = Environment.getExternalStorageDirectory().getPath() + File.separator + AssetConstants.PANDIAN_EXPFILE_NAME;
                File destFile = new File(filepath);
                try {
                    CryptoUtil.writeFile(SMUtil.encryptBySM2(pubKey, CryptoUtil.readFile(srcFile)), destFile);
                    FileUtils.forceDelete(srcFile);
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_FILE_EXPORT_SUCCESS, Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                    Logger.e(e.getMessage());
                } catch (JAFCryptoException e) {
                    Log.e(TAG, e.getMessage());
                    Logger.e(e.getMessage());
                }
            }
        });

        //扫描条形码
        scanBarcodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent scanIntent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(scanIntent, 0);
            }
        });

        //查询设备状态
        searchBarcodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent intent = new Intent(MainActivity.this, AssetDetailActivity.class);
                intent.putExtra(AssetConstants.SEARCHBYBARCODE, resultEditView.getText().toString());
                startActivity(intent);*/
                final String barCode = resultEditView.getText().toString();
                final String filePath = MainActivity.this.getFilesDir().getAbsoluteFile() + File.separator + AssetConstants.PANDIAN_TMPFILE_NAME;
                if (barCode == null || AssetConstants.STR_EMPTY.equals(barCode)) {

                } else if (barCode.length() != AssetConstants.BARCODE_BIT) {
                    Toast.makeText(MainActivity.this, AssetConstants.MSG_BARCODE_BIT_VALID, Toast.LENGTH_LONG).show();
                } else {
                    new Thread() {
                        @Override
                        public void run() {

                            super.run();
                            //bufferRead();
                            //readRandom();
                            PandianFileUtils.searchRecord(searchRecvHandler, barCode, filePath);
                        }


                    }.start();
                }


            }
        });

        //查询所有盘点设备
        searchCheckinBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Logger.addLogAdapter(new AndroidLogAdapter() );
                //Logger.e("message");
                Intent intent = new Intent(MainActivity.this, AssetActivity.class);
                intent.putExtra(AssetConstants.PANDIAN_FLG, AssetConstants.PANDIAN);
                startActivity(intent);
                //handler内存泄漏检测用
                //searchRecvHandler.sendEmptyMessageDelayed(0,20000);
            }
        });

        //查询所有未盘点设备
        searchNoCheckinBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AssetActivity.class);
                intent.putExtra(AssetConstants.PANDIAN_FLG, AssetConstants.NO_PANDIAN);
                startActivity(intent);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            Logger.d("scan barcode: %s", scanResult);
            resultEditView.setText(scanResult);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        searchRecvHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 防止内存泄漏，增加弱引用
     */
    private static class MainRecvHandler extends Handler {

        private final WeakReference<MainActivity> mActivity;

        public MainRecvHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity _activity = mActivity.get();

            switch (msg.what) {
                case 0:
                    //没有检索到数据
                    Toast.makeText(_activity, AssetConstants.MSG_NO_FIND_ASSET, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    //检索到数据
                    _activity.setSearchRecodeBundle(msg.getData());
                    String isPandian
                            = _activity.getSearchRecodeBundle()
                            .getString(AssetConstants.PRODUCT_COLNAME_PANDIANFLG);

                    if (AssetConstants.PANDIAN.equals(isPandian)) {
                        //已盘点
                        Toast.makeText(_activity, AssetConstants.MSG_ASSET_PANDIAN, Toast.LENGTH_LONG).show();
                    } else {
                        Intent intent = new Intent(_activity, AssetDetailActivity.class);
                        intent.putExtra(AssetConstants.SEARCHBYBARCODE, _activity.getResultEditView().getText().toString());
                        intent.putExtra(AssetConstants.ASSET_RECORD, _activity.getSearchRecodeBundle());
                        _activity.startActivity(intent);
                    }
                    break;
            }
        }
    }

    public void setResultEditView(EditText resultEditView) {
        this.resultEditView = resultEditView;
    }

    public void setSearchRecodeBundle(Bundle searchRecodeBundle) {
        this.searchRecodeBundle = searchRecodeBundle;
    }

    public EditText getResultEditView() {

        return resultEditView;
    }

    public Bundle getSearchRecodeBundle() {
        return searchRecodeBundle;
    }
}
